package com.java.map;

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.junit.Test;

import com.collection.model.Student;

/**
 * TreeMapTest测试类
 *		TreeMap
 *			键是红黑树结构，可以保证键的排序(根据key值对元素进行排序)和唯一性
 *		重点：测试TreeMap的排序机制；
 * @author LC
 *
 */
public class TreeMapTest {
	
	/**
	 * TreeMap测试01
	 * 使用TreeMap的无参构造对map集合进行排序——自然排序
	 * 		默认调用key值对应的基本数据类型，引用数据类型的实现了Comparable接口的默认排序器对map元素进行排序
	 */
	@Test
	public void testTreeMap_01() {
		Map<String, String> map = new TreeMap<>() ;
		
		map.put("002", "上海市") ;
		map.put("001", "北京市") ;
		map.put("004", "天津市") ;
		map.put("003", "河南省") ;
		//为保证map键值的唯一性，此键值为'001'的元素将会覆盖前面添加出现过的key值为'001'的元素
		map.put("001", "周口市") ;
		
		System.out.println("遍历输出map集合中所有的元素");
		Set<Entry<String, String>> objects = map.entrySet() ;
		Iterator<Entry<String, String>> iterator = objects.iterator() ;
		while(iterator.hasNext()) {
			Entry<String, String> entry = iterator.next() ;
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
	}
	
	/**
	 * TreeMap测试02
	 * 自定义TreeMap的Comparable排序器对map集合中的元素进行排序
	 */
	@Test
	public void testTreeMap_02() {
		Map<Student, String> map = new TreeMap<>(new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
				//主要条件
				int num = s1.getAge() - s2.getAge() ;
				//次要条件
				int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num ;
				
				return num2;
			}
			
		}) ;
		
		Student student01 = new Student("张三01",21) ;
		Student student02 = new Student("张三02",22) ;
		Student student03 = new Student("张三03",23) ;
		Student student04 = new Student("张三04",24) ;
		
		map.put(student02, "002") ;
		map.put(student01, "001") ;
		map.put(student03, "003") ;
		map.put(student04, "004") ;
		map.put(student02, "002") ;
		
		System.out.println("遍历输出map集合中所有的元素");
		Set<Entry<Student, String>> objects = map.entrySet() ;
		Iterator<Entry<Student, String>> iterator = objects.iterator() ;
		while(iterator.hasNext()) {
			Entry<Student, String> entry = iterator.next() ;
			System.out.println(entry.getKey() + ":" +entry.getValue());
		}
		
		
		
	}

}
